package com.hnit.applet.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.hnit.applet.entity.OnlyOfficeDo;
import com.hnit.applet.utils.LambdaUtils;
import com.hnit.applet.utils.MinioUtil;
import io.minio.StatObjectResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zwj
 * @description: 文件上传下载测试
 * @data: 2022/6/17
 **/
@RestController
@RequestMapping("minio")
@Api(tags = "minio文件服务测试")
public class MinioController {

    @Resource
    private MinioUtil minioUtil;

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    public String uploadFile(MultipartFile file) {
        String name = file.getOriginalFilename();
        minioUtil.upload(file, name);
        return name;
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载", notes = "下载")
    public void download(HttpServletResponse response, @RequestParam(value = "name") String name) {
        try {
            StatObjectResponse statObjectResponse = minioUtil.statObject(name);
            byte[] download = minioUtil.download(name);
            response.setContentType(statObjectResponse.contentType());
            response.setHeader("Content-disposition", "attachment;filename=\"" + URLEncoder.encode(name, "UTF-8") +
                    "\"");
            OutputStream out = response.getOutputStream();
            BufferedOutputStream output = new BufferedOutputStream(out);
            output.write(download);
            response.flushBuffer();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/preview")
    @ApiOperation(value = "合同下载", notes = "合同下载")
    public void downloadContractTemplate(HttpServletResponse response) throws IOException {
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                    minioUtil.download("test.docx"));
            Map<String, Object> map = new HashMap<>(16);
            map.put("contractCode", "测试1");
            map.put("contractCode", "测试2");
            map.put("contractCode1", "测试3");
            // 在文档中需要替换插入表格的位
            String key = "$key";

            NiceXWPFDocument xwpfDocument = XWPFTemplate.compile(byteArrayInputStream).render(map).getXWPFDocument();
            List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
            paragraphs.forEach(e -> {
                List<XWPFRun> runs = e.getRuns();
                runs.forEach(LambdaUtils.consumerWithIndex((r, index) -> {
                    String text = r.getText(0).trim();
                    if (text.contains(key)) {
                        r.setText(text.replace(key, ""), 0);
                        XmlCursor cursor = e.getCTP().newCursor();
                        // 在指定游标位置插入表格
                        XWPFTable table = xwpfDocument.insertNewTbl(cursor);
                        CTTblPr tablePr = table.getCTTbl().getTblPr();
                        CTTblWidth width = tablePr.addNewTblW();
                        width.setW(BigInteger.valueOf(8500));
                        this.inserInfo(table);
                    }
                }));
            });


            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=\"" + URLEncoder.encode("111" + ".docx"
                    , "UTF-8") + "\"");
            OutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            xwpfDocument.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(xwpfDocument, bos, out);
        } catch (IOException e) {
            response.getWriter().write("<p>下载出错，请稍后再试！</p>");
            response.getWriter().flush();
        }
    }

    /**
     * 把信息插入表格
     *
     * @param table
     */
    private void inserInfo(XWPFTable table) {
        List<OnlyOfficeDo> list = new ArrayList<>();
        OnlyOfficeDo onlyOfficeDo = new OnlyOfficeDo();
        onlyOfficeDo.setFileUrl("1111");
        onlyOfficeDo.setError("2222");
        onlyOfficeDo.setFileType("333333");
        list.add(onlyOfficeDo);
        XWPFTableRow row = table.getRow(0);
        //默认会创建一列，即从第2列开始
        for (int col = 1; col < 6; col++) {
            // 第一行创建了多少列，后续增加的行自动增加列
            row.createCell().getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(8500));
        }
        row.getCell(0).setText("指标");
        row.getCell(1).setText("指标说明");
        row.getCell(2).setText("公式");
        row.getCell(3).setText("参考值");
        row.getCell(4).setText("说明");
        row.getCell(5).setText("计算值");
        list.forEach(e -> {
            XWPFTableRow row1 = table.createRow();
            row1.getCell(0).setText(e.getFileUrl());
            row1.getCell(1).setText(e.getError());
            row1.getCell(2).setText(e.getFileType());
        });
    }


}
